import { history  } from '@umijs/max';
import { getDefaultPathName, getUser } from '@/utils/util';
import { useState } from 'react';

// 需要特殊处理的路由 存在的话删除重新加入
const SpecialMaps = {};

/**
 * 处理全局页头部分的路由栈 处理
 */
const hasRoute = (arr = [], key, value) => arr.some((item) => item[key] === value);
const getActiveKey = (arr = [], index) => arr[index + 1] ?? arr[index - 1]; // 优先先后取一位, 否则就向前一位
const hasActiveByKeys = (value, keys = []) => keys.some((key) => value.indexOf(key) > -1);

const useTabRouter = ({ defaultRoute, defaultActiveKey, menudata }) => {
  // const history = useHistory();
  // const { formatMessage } = useIntl();
  const defaultPathName = getDefaultPathName();
  const mergeRoute = defaultRoute ?? [];
  const mergeActiveKey = defaultActiveKey ?? defaultPathName;
  const [routers, setRouters] = useState(mergeRoute);
  const [activeKey, setActiveKey] = useState(mergeActiveKey);

  /**
   *
   * @param {*} pathname 路由名
   * @param {*} query query
   * @param {*} title 标题
   * @param {*} force 是否强制更新标题
   */
    // 路由栈只能进栈单个的路由 更新 query 和 title
  const updateOne = (pathname, search, title = '', force) => {
      const copyRouters = [...routers];
      if (!routers?.length) {
        return;
      }
      const current = copyRouters?.find((item) => item?.pathname === pathname);
      if (current === undefined) return;
      current.search = search;
      if (force) current.title = title;
      setRouters(copyRouters);
    };

  const overflowRouters = () => {
    let tempRouters = [];
    let header = [];
    const userInfo = getUser();
    const targetRoute = userInfo?.menus?.[0]?.children?.[0]?.path;
    if (routers?.[0]?.pathname.indexOf(targetRoute) > -1) {
      tempRouters = routers.slice(1);
      header = routers.slice(0, 1);
    } else {
      tempRouters = [...routers];
    }
    tempRouters.splice(1,1);
    if (header.length) {
      setRouters([...header, ...tempRouters]);
    } else {
      setRouters(tempRouters);
    }
  };

  const replaceRouteByPathname = (pathname, route) => {
    const copyRouters = [...routers];
    const currentIndex = copyRouters.findIndex((item) => item.pathname === pathname);
    const currentRoute = copyRouters?.[currentIndex];
    const mergeRoutes = { ...currentRoute, ...route, key: route?.query?.venId };
    if (currentIndex !== -1) {
      copyRouters.splice(currentIndex, 1, mergeRoutes);
    }
    setRouters(copyRouters);
  };
  /**
   * create or update a route object into stack
   * @param {*} route 路由信息
   *  - @param { pathname }
   * @param {*} force 是否需要强制更新title
   * @param text
   * */
  const addRouters = (route, force = false, text = '') => {
    try {
      const hasActivedRoute = hasRoute(routers, 'pathname', route.pathname);
      const currentRoute = menudata?.breadcrumbMap?.get(route.pathname);
      const title = text || currentRoute?.name;


      if (hasActivedRoute && SpecialMaps[route.pathname]) {
        replaceRouteByPathname(route.pathname, route);
        setActiveKey(route.pathname);
        return;
      }
      if (!hasActivedRoute) {
        setRouters((state) =>
          state.concat({
            ...route,
            content: currentRoute?.component,
            exact: currentRoute?.exact,
            title,
            currentRoute,
          }),
        );
      } else {
        updateOne(route.pathname, route.search, title, force);
      }
      setActiveKey(route.pathname);
    } catch (err) {
      console.log(err);
    }
  };

  /**
   * remove route stack by dynamic key e.g pathname or uni key
   * @param {*} value
   * @param {*} key
   */
  const removeRoute = (value, key = 'pathname') => {
    const store = [...routers];
    // 获取当前Tab的Index, 移除当前节点之后, 先后一位取Tab
    const index = store.findIndex((route) => route[key] === value);
    const currentActiveObj = getActiveKey(routers, index);
    store.splice(index, 1);
    setRouters(store);
    if (currentActiveObj) {
      setActiveKey(currentActiveObj?.pathname); // 设置激活值
      history.push({ pathname: currentActiveObj.pathname, query: currentActiveObj.query });
    } else {
      history.push({ pathname: mergeActiveKey });
    }
  };

  // 只是移除路由信息, 移除后不再跳转
  const removeRouteOne = (value, key = 'pathname') => {
    const store = [...routers];

    const filters = store.filter((route) => route[key] !== value);

    setRouters(filters);
    return Promise.resolve(routers);
  };

  // 更新已存在的route的信息
  const updateRouteByPathname = (pathname = 'pathname', meta = {}) => {
    const store = [...routers];

    const currIndex = store.findIndex((route) => route.pathname === pathname);

    let currRoute = store[currIndex];

    currRoute = {
      ...currRoute,
      ...meta,
    };

    store.splice(currIndex, 1, currRoute);

    setRouters(store);
  };

  /**
   * clear all route stack
   * exclude root or dashboard pathname
   * maybe has multi dashboard pathname
   *
   * @param otherExcludes
   */
  const cleanup = (otherExcludes) => {
    const excludes = [...defaultRoute];
    if (Array.isArray(otherExcludes) && otherExcludes.length > 0) {
      const excludeRoutes = routers?.filter((item) =>
        hasActiveByKeys(item.pathname, otherExcludes),
      );
      excludes.push(...excludeRoutes);
    }
    const cleanActiveKey = excludes?.[excludes.length - 1]?.pathname;
    setActiveKey(activeKey ?? cleanActiveKey); // 重置Key为激活值
    setRouters(excludes); // 清空全部路由栈
    history.push({ pathname: cleanActiveKey });
  };

  return {
    routers,
    activeKey,
    setActiveKey,
    removeRoute,
    cleanup,
    addRouters,
    overflowRouters,
    removeRouteOne,
    updateRouteByPathname,
  };
};

export default useTabRouter;
